import React, { Component } from 'react'
import { connect } from 'react-redux'
import { createContainer } from 'utils/hoc'
import { Form, Row, Input, Switch, message, Popconfirm, Modal, Select, Button } from 'antd'
import ContentBox from 'components/contentBox'
import Filters from 'components/common/filters'
import CustomTable from 'components/common/table'
import Authorized from 'components/common/authorized'
import { SCENE_TYPE, CHECK_STATUE, widgetType } from 'constants'
import PropTypes from 'prop-types'

import Style from './list.css'

const { TextArea } = Input
const { Option } = Select
const formItemLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 16 }
}
// const layout = {
//   labelCol: { span: 6 },
//   wrapperCol: { span: 16 }
// }

// const formTailLayout = {
//   labelCol: { span: 6 },
//   wrapperCol: { span: 9, offset: 2 }
// }

// const auditRadio = [
//   { label: '不限', value: '' },
//   { label: '已通过', value: 'PASS' },
//   { label: '未审核', value: 'WAITING' }
// ]

// // 上架状态
// const shelvesRadio = [
//   { label: '不限', value: '' },
//   { label: '已上架', value: '1' },
//   { label: '未上架', value: '0' }
// ]
// // 上新状态
// const newRadio = [
//   { label: '不限', value: '' },
//   { label: '上新中', value: '1' },
//   { label: '非上新', value: '0' }
// ]
// // 推荐状态
// const recommendRadio = [
//   { label: '不限', value: '' },
//   { label: '推荐中', value: '1' },
//   { label: '非推荐', value: '0' }
// ]

// // 场景类型
// const scenesRadio = [
//   { label: '不限', value: '' },
//   { label: '人文空间', value: 'HUMAN_SPACE' },
//   { label: '室内家具', value: 'FAMILY_SPACE' },
//   { label: '商业空间', value: 'BIZ_SPACE' },
//   { label: '公共空间', value: 'COMMON_SPACE' }
// ]

class list extends Component {
  static propTypes = {
    form: PropTypes.any
  }
  constructor (props) {
    super(props)
    this.state = {
      pageNo: 1,
      pageSize: 20,
      params: {},
      editParams: {}
    }
    this.handleReset = this.handleReset.bind(this)
    this.handleSubmit = this.handleSubmit.bind(this)
    this.onPageChange = this.onPageChange.bind(this)
    this.onShowSizeChange = this.onShowSizeChange.bind(this)
    this.handleOk = this.handleOk.bind(this)
    this.handleCancel = this.handleCancel.bind(this)
  }

  getFilterCols (staffValue) {
    return [
      {
        label: '输入搜索',
        id: 'queryNo',
        widget: widgetType.input,
        placeholder: '请输入场景编号/场景名称'
      }, {
        label: '审核状态',
        id: 'auditStatus',
        widget: widgetType.select,
        placeholder: '请选择',
        options: [{
          text: '不限',
          value: ''
        }, {
          text: '已通过',
          value: 'PASS'
        }, {
          text: '未审核',
          value: 'WAITING'
        }, {
          text: '未通过',
          value: 'REFUSE'
        }]
      }, {
        label: '上架状态',
        id: 'putAway',
        widget: widgetType.select,
        placeholder: '请选择',
        options: [{
          text: '不限',
          value: ''
        }, {
          text: '已上架',
          value: '1'
        }, {
          text: '未上架',
          value: '0'
        }]
      }, {
        label: '上新状态',
        id: 'updateFlag',
        widget: widgetType.select,
        placeholder: '请选择',
        options: [{
          text: '不限',
          value: ''
        }, {
          text: '上新中',
          value: '1'
        }, {
          text: '非上新',
          value: '0'
        }]
      }, {
        label: '推荐状态',
        id: 'recommendFlag',
        widget: widgetType.select,
        placeholder: '请选择',
        options: [{
          text: '不限',
          value: ''
        }, {
          text: '推荐中',
          value: '1'
        }, {
          text: '非推荐',
          value: '0'
        }]
      }, {
        label: '场景类型',
        id: 'categoryCodeSearch',
        widget: widgetType.select,
        placeholder: '请选择',
        options: [{
          text: '不限',
          value: ''
        }, {
          text: '人文空间',
          value: 'HUMAN_SPACE'
        }, {
          text: '室内家具',
          value: 'FAMILY_SPACE'
        }, {
          text: '商业空间',
          value: 'BIZ_SPACE'
        }, {
          text: '公共空间',
          value: 'COMMON_SPACE'
        }, {
          text: '展馆空间',
          value: 'PAVILION_SPACE'
        }, {
          text: '其他空间',
          value: 'OTHER_SPACE'
        }]
      }, {
        label: '场景创建者',
        id: 'createUser',
        widget: widgetType.select,
        props: {
          showSearch: true
        },
        placeholder: '请选择',
        options: staffValue ? this.dealStaff(staffValue) : []
      }, {
        label: false,
        span: 16,
        key: 'custom',
        widget: 'custom',
        formItemLayout: {},
        render: () => {
          return (
            <>
              <Button type='primary' style={{ marginRight: 10 }} onClick={this.handleSubmit}>查询</Button>
              <Button style={{ marginRight: 10 }} onClick={this.handleReset}>重置</Button>
            </>
          )
        }
      }
    ]
  }

  getTableCols () {
    return [
      {
        title: '场景编号',
        dataIndex: 'id',
        key: 'id',
        width: 120
      },
      {
        title: '场景名称',
        dataIndex: 'name',
        key: 'name',
        width: 120
      },
      {
        title: '场景类型',
        dataIndex: 'categoryCode',
        key: 'categoryCode',
        width: 100,
        render: (text) => SCENE_TYPE[text]
      },
      {
        title: '场景图片',
        dataIndex: 'image',
        key: 'image',
        width: 80,
        render: text => <img className={Style['image']} src={text} />
      },
      {
        title: '标签',
        dataIndex: 'label',
        key: 'label',
        width: 100,
        render: (text, record) => {
          return <>
            <div>上架：<Switch size='small' defaultChecked={record.putAway} onChange={(checked) => this.handlePutOn(checked, record.id)} /></div>
            <div>上新：<Switch size='small' defaultChecked={record.updateFlag} onChange={(checked) => this.handleNew(checked, record.id)} /></div>
            <div>推荐：<Switch size='small' defaultChecked={record.recommendFlag} onChange={(checked) => this.handleRecommend(checked, record.id)} /></div>
          </>
        }
      },
      {
        title: '点击量',
        dataIndex: 'exchangeChannel',
        key: 'exchangeChannel',
        width: 70,
        render: text => {
          return text || '-'
        }
      },
      {
        title: '审核状态',
        dataIndex: 'auditStatus',
        key: 'auditStatus',
        render: text => {
          return <div>
            {CHECK_STATUE[text] || '-'}
            {/* {
              text === 'PASS' && <a>审核详情</a>
            } */}
          </div>
        },
        width: 100
      },
      {
        title: '操作',
        dataIndex: 'operate',
        key: 'operate',
        width: 130,
        render: (text, record, index) => {
          return <>
            <div className={Style['a-container']}>
              <a onClick={() => this.handleEdit(record)}>编辑</a>
              <a target='_blank' href={`${window.location.origin}/scenes/details/${record.id}`}>查看</a>
              <a target='_blank' href={`${window.location.origin}/scenes/edit/${record.id}`}>修改</a>
            </div>
            <div className={Style['a-container']}>
              <Authorized auth='SCENE:MANAGE:DEL'>
                <Popconfirm placement='top' title='确认是否删除场景' onConfirm={() => this.handleDelete(record.id)}>
                  <a>删除</a>
                </Popconfirm>
              </Authorized>
              <Authorized auth='SCENE:MANAGE:AUDIT'>
                {
                  record.auditStatus === 'WAITING' && <Popconfirm placement='top' okText='通过' cancelText='不通过' title='确认是否审核场景' onConfirm={() => this.handleAudit(record.id, true, index)} onCancel={() => this.handleAudit(record.id, false, index)}>
                    <a>审核</a>
                  </Popconfirm>
                }
              </Authorized>
            </div>
          </>
        }
      }
    ]
  }

  dealStaff (value) {
    value && value.list.forEach(element => {
      element.value = element.name
      element.text = element.name
    })
    return value.list || []
  }

  handleSubmit () {
    const { pageSize, pageNo } = this.state
    const { staffData } = this.props
    // eslint-disable-next-line handle-callback-err
    this.props.form.validateFieldsAndScroll((err, values) => {
      values.categoryCode && delete values.categoryCode
      values.name && delete values.name
      values.description && delete values.description

      if (values.categoryCodeSearch) {
        values.categoryCode = values.categoryCodeSearch
        delete values.categoryCodeSearch
      }

      for (let key in values) {
        if (!values[key]) {
          delete values[key]
        }
      }

      if (values.createUser) {
        staffData.list.forEach(item => {
          if (item.name === values.createUser) {
            values.createUser = item.userId
          }
        })
      }

      this.setState({
        params: values
      })
      values.pageNo = pageNo
      values.pageSize = pageSize
      this.props.getSceneList(values)
    })
  }

  handleReset () {
    this.setState({
      pageSize: 20,
      pageNo: 1,
      params: {}
    })
    this.props.form.resetFields()
    this.props.getSceneList({
      pageSize: 20,
      pageNo: 1
    })
  }

  onPageChange (pageNo, pageSize) {
    const { params } = this.state
    params.pageNo = pageNo
    params.pageSize = pageSize
    this.setState({
      pageNo
    })
    this.props.getSceneList(params)
  }

  onShowSizeChange (current, pageSize) {
    this.setState({
      pageSize
    })
    const { params } = this.state
    params.pageNo = current
    params.pageSize = pageSize
    this.props.getSceneList(params)
  }

  // 删除
  handleDelete (id) {
    this.props.deleteScene({
      sceneId: id
    })
  }

  // 上架
  handlePutOn (checked, id) {
    this.props.handlePutOn({
      sceneId: id,
      putAway: checked ? 1 : 0
    })
  }
  // 上新
  handleNew (checked, id) {
    this.props.handleNew({
      sceneId: id,
      updateFlag: checked ? 1 : 0
    })
  }
  // 推荐
  handleRecommend (checked, id) {
    this.props.handleRecommend({
      sceneId: id,
      recommendFlag: checked ? 1 : 0
    })
  }

  // 审核
  handleAudit (id, status, index) {
    const { pageNo, pageSize } = this.state
    localStorage.setItem('scenesPageNo', pageNo)
    localStorage.setItem('scenesPageSize', pageSize)
    this.setState({
      auditStatus: status,
      auditStatusIndex: index
    })
    this.props.handleCheck({
      sceneId: id,
      auditStatus: status ? 'PASS' : 'REFUSE'
    })
  }

  // 查看
  handleView (id) {
    const { pageNo, pageSize } = this.state
    localStorage.setItem('scenesPageNo', pageNo)
    localStorage.setItem('scenesPageSize', pageSize)
    this.props.router.push(`/scenes/details/${id}`)
  }

  // 修改
  handleFix (id) {
    // const { pageNo, pageSize } = this.state
    // localStorage.setItem('scenesPageNo', pageNo)
    // localStorage.setItem('scenesPageSize', pageSize)
    // this.props.router.push(`/scenes/edit/${id}`)
  }

  // 编辑
  handleEdit (params) {
    const { pageNo, pageSize } = this.state
    localStorage.setItem('scenesPageNo', pageNo)
    localStorage.setItem('scenesPageSize', pageSize)

    this.setState({
      editParams: params,
      showEdit: true
    })
  }

  handleOk () {
    const { editParams } = this.state
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const params = {
          categoryCode: values.categoryCode,
          description: values.description,
          name: values.name,
          sceneId: editParams.id
        }
        this.props.fixScene(params)
      }
    })
  }

  handleCancel () {
    this.setState({
      showEdit: false
    })
  }

  componentDidMount () {
    const { pageSize, pageNo } = this.state
    const scenesPageNo = localStorage.getItem('scenesPageNo') && Number(localStorage.getItem('scenesPageNo'))
    const scenesPageSize = localStorage.getItem('scenesPageSize') && Number(localStorage.getItem('scenesPageSize'))

    this.props.getSceneList({
      pageSize: scenesPageSize || pageSize,
      pageNo: scenesPageNo || pageNo
    })
    scenesPageNo && this.setState({
      pageNo: scenesPageNo
    })
    scenesPageSize && this.setState({
      pageSize: scenesPageSize
    })
    this.props.getStaffList({
      pageNo: 1,
      pageSize: 999
    })
  }

  componentWillReceiveProps (nextProps) {
    if (!this.props.restoreRequest && nextProps.restoreRequest) {
      message.success('还原成功')
      this.handleSubmit()
    }

    if (!this.props.deleteRequest && nextProps.deleteRequest) {
      message.success('删除成功')
      this.handleSubmit()
    }

    // 审核
    if (!this.props.checkRequest && nextProps.checkRequest) {
      message.success('操作成功')
      // this.handleSubmit()
      this.props.handleCheckEdit({
        auditStatus: this.state.auditStatus,
        index: this.state.auditStatusIndex
      })
    }
    // 审核
    if (!this.props.checkEditRequest && nextProps.checkEditRequest) {
      message.success('操作成功')
    }

    if (!this.props.fixRequest && nextProps.fixRequest) {
      message.success('编辑成功')
      this.setState({
        showEdit: false
      })
      this.props.form.resetFields()
      setTimeout(() => {
        this.handleSubmit()
      }, 0)
    }

    if (!this.props.sceneData && nextProps.sceneData) {
      localStorage.removeItem('scenesPageNo')
      localStorage.removeItem('scenesPageSize')
    }
  }

  render () {
    const { pageNo, pageSize, editParams, showEdit } = this.state
    const { getFieldDecorator } = this.props.form
    const { sceneData, form, staffData } = this.props
    const pagination = {
      showSizeChanger: true,
      current: pageNo,
      total: sceneData && sceneData.total,
      onChange: this.onPageChange,
      onShowSizeChange: this.onShowSizeChange,
      pageSize
    }

    return (
      <>
        <ContentBox>
          <div className={Style['scenes-list-container']}>
            <Row>
              <Filters
                cols={this.getFilterCols(staffData)}
                form={form}
                actions={false}
                // search={this.handleSubmit}
                // reset={this.handleReset}
              />
              {/* <Form {...layout} size='middle'>
                <Row gutter={24}>
                  <Col span={9}>
                    <Form.Item label='场景编号'>
                      {
                        getFieldDecorator('queryNo')(
                          <Input placeholder='请输入场景编号' />
                        )
                      }
                    </Form.Item>
                  </Col>
                </Row>
                <Row gutter={24} style={{ marginTop: '-10px' }}>
                  <Col span={9}>
                    <Form.Item label='审核状态'>
                      {
                        getFieldDecorator('auditStatus', {
                          initialValue: ''
                        })(
                          <Radio.Group options={auditRadio} />
                        )
                      }

                    </Form.Item>
                  </Col>
                  <Col span={9}>
                    <Form.Item label='上架状态'>
                      {
                        getFieldDecorator('putAway', {
                          initialValue: ''
                        })(
                          <Radio.Group options={shelvesRadio} />
                        )
                      }

                    </Form.Item>
                  </Col>
                </Row>
                <Row gutter={24}>
                  <Col span={9}>
                    <Form.Item label='上新状态'>
                      {
                        getFieldDecorator('updateFlag', {
                          initialValue: ''
                        })(
                          <Radio.Group options={newRadio} />
                        )
                      }

                    </Form.Item>
                  </Col>
                  <Col span={9}>
                    <Form.Item label='推荐状态'>
                      {
                        getFieldDecorator('recommendFlag', {
                          initialValue: ''
                        })(
                          <Radio.Group options={recommendRadio} />
                        )
                      }
                    </Form.Item>
                  </Col>
                </Row>
                <Row gutter={20}>
                  <Form.Item label='场景类型' {...{ labelCol: { span: 2 },
                    wrapperCol: { span: 16 } }}>
                    {
                      getFieldDecorator('categoryCodeSearch', {
                        initialValue: ''
                      })(
                        <Radio.Group options={scenesRadio} />
                      )
                    }
                  </Form.Item>
                </Row>
                <Row gutter={24}>
                  <Col span={9}>
                    <Form.Item {...formTailLayout}>
                      <Button type='primary' onClick={this.handleSubmit}>查询</Button>
                      <Button style={{ marginLeft: '10px' }} onClick={this.handleReset}>重置</Button>
                    </Form.Item>
                  </Col>
                </Row>
              </Form> */}
            </Row>
            <Row>
              <CustomTable loading={!sceneData} columns={this.getTableCols()} dataSource={(sceneData && sceneData.sceneList) || []} pagination={pagination} />
            </Row>
          </div>
          <Modal
            title='编辑场景'
            visible={showEdit}
            width={600}
            onOk={this.handleOk}
            destroyOnClose
            onCancel={this.handleCancel}
          >
            <Form {...formItemLayout}>
              <Form.Item label='场景名称'>
                {getFieldDecorator('name', {
                  rules: [{ required: true, message: '请输入场景名称' }],
                  initialValue: editParams.name
                })(
                  <Input placeholder='请输入' />
                )}
              </Form.Item>
              <Form.Item label='场景描述'>
                {getFieldDecorator('description', {
                  rules: [{ required: true, message: '请输入场景描述' }],
                  initialValue: editParams.description
                })(
                  <TextArea placeholder='请输入场景描述' />
                )}
              </Form.Item>
              <Form.Item label='场景类别'>
                {getFieldDecorator('categoryCode', {
                  rules: [{ required: true, message: '请选择场景类别' }],
                  initialValue: editParams.categoryCode
                })(
                  <Select placeholder='请选择场景类别'>
                    <Option value='HUMAN_SPACE'>人文空间</Option>
                    <Option value='FAMILY_SPACE'>家居室内</Option>
                    <Option value='BIZ_SPACE'>商业空间</Option>
                    <Option value='COMMON_SPACE'>公共空间</Option>
                    <Option value='PAVILION_SPACE'>展馆空间</Option>
                    <Option value='OTHER_SPACE'>其他空间</Option>
                  </Select>
                )}
              </Form.Item>
            </Form>
          </Modal>
        </ContentBox>
      </>
    )
  }
}

const mapState = state => ({
  staffData: state.setup.staffData,
  sceneData: state.scene.sceneData,
  restoreRequest: state.scene.restoreRequest,
  deleteRequest: state.scene.deleteRequest,
  checkRequest: state.scene.checkRequest,
  fixRequest: state.scene.fixRequest,
  checkEditRequest: state.scene.checkEditRequest
})
const mapDispatch = dispatch => ({
  getSceneList: dispatch.scene.getSceneList,
  deleteScene: dispatch.scene.deleteScene,
  handlePutOn: dispatch.scene.handlePutOn, // 上架
  handleRecommend: dispatch.scene.handleRecommend, // 推荐
  handleNew: dispatch.scene.handleNew, // 上新
  handleCheck: dispatch.scene.handleCheck,
  fixScene: dispatch.scene.fixScene,
  getStaffList: dispatch.setup.getStaffList,
  handleCheckEdit: dispatch.scene.handleCheckEdit
})
const Formlist = Form.create()(list)

export default createContainer(
  connect(
    mapState,
    mapDispatch
  )(Formlist)
)
